package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.entity.UserDto;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.parser.HttpParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        log.info("获取验证码 user:{}",user);
        // 1.产生一个4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4)+"";
        log.info("验证码：{}",code);
        // 2.调用阿里云发短信，开发的时候，可以不掉，最后的时候加上

        // 3.把验证码存入session，后续登录时，进行验证
        //session.setAttribute(user.getPhone(),code);
        // 把验证码存入redis
        redisTemplate.opsForValue().set(user.getPhone(),code,5, TimeUnit.MINUTES);
        return R.success("获取验证码成功！");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto, HttpSession session){
        log.info("[验证码登录 dto:{},{}]",userDto.getPhone(),userDto.getCode());
        // 1.先判断验证码是否正确,不需要强转
        //Object codeInSession = session.getAttribute(userDto.getPhone());
        // 从redis中根据手机号取验证码
        Object codeInSession = redisTemplate.opsForValue().get(userDto.getPhone());
        // 让session的code与用户传递过来的code做完全匹配
        if(codeInSession != null && codeInSession.toString().equals(userDto.getCode())){
            // 2.如果验证通过，偷偷帮用户注册，先去数据库查询一下是否有这个用户，根据手机号一定找到一条记录
            // select * from user where phone = ''
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(User::getPhone,userDto.getPhone());
            // MP用的POJO,Mapper一定用的POJO
            User one = userService.getOne(lambdaQueryWrapper);
            if(one == null){
                // 数据库中无这条记录，感觉去给注册
                User user = new User();
                user.setPhone(userDto.getPhone());
                // 其它字段，根据产品需求去初始化
                user.setStatus(1);
                userService.save(user);
                // 存盘后，把user的id存入session
                session.setAttribute("user",user.getId());
            }else{
                // 把从数据库获取到的对象的id存入Session
                session.setAttribute("user",one.getId());
            }
            // 无论哪种种情况，最终把用户的ID存入session，后续用户下单，购物车，收货地址，都需要当前用户ID
            redisTemplate.delete(userDto.getPhone());
            return R.success("登录成功");
        }
        // 其它情况就是登录失败
        return R.error("登录失败，验证码无效或过期");
    }

}
